package com.weixin.program.task;

import com.weixin.program.config.WeixinProperties;
import com.weixin.program.delay.DelayQueueTask;
import com.weixin.program.po.Record;
import com.weixin.program.ro.UserData;
import com.weixin.program.service.RecordService;
import com.weixin.program.utils.BeanTool;
import com.weixin.program.utils.HttpClientProxy;
import com.weixin.program.utils.TemplateUtil;
import com.weixin.program.utils.WeixinUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ConsumerTask extends Thread {

    @Override
    public void run() {

        WeixinProperties properties = BeanTool.getBean(WeixinProperties.class);

        while (true) {
            try {
                DelayQueue<Task> delayQueue = DelayQueueTask.getDelayQueue();
                Task task = delayQueue.take();
                String taskName = task.getTaskName();
                log.info(taskName + "取出成功,当前时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                String userId = task.getToUserId();
                String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                RecordService recordService = BeanTool.getBean(RecordService.class);
                Record records = recordService.selectByUserIdAndTime(userId, dateTime);
                if (records != null && records.getStatus() == 1) {
                    DelayQueueTask.clearDelayQueue();
                    log.info("用户已打卡,取消重试任务,队列任务数为:{}", delayQueue.size());

                    try {
                        String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
                        String touserid = properties.getTouserid();
                        UserData userData = WeixinUtil.getUserData(touserid, token);
                        String remindMsg = TemplateUtil.buildNoticeDoneMsg(properties.getTouserid(), userData.getNickName(), properties.getRemindtemplateid());
                        log.info("发送提醒消息内容:{}", remindMsg);
                        String sendUrl = properties.getTemplateurl() + token;
                        String response = HttpClientProxy.post(sendUrl, remindMsg);
                        log.info("发送提醒消息响应:{}", response);
                    } catch (Exception e) {
                        log.info("重试任务发送提醒消息时发生异常,异常信息:{}", e);
                    }

                } else {
                    if (delayQueue.size() == 0) {
                        String notDoneTaskName = "【未打卡通知任务】";
                        long milliLong = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                        int delayTime = properties.getNotice();
                        Task notDoneTask = new Task(notDoneTaskName, properties.getTouserid(), milliLong, delayTime, TimeUnit.SECONDS);
                        DelayQueueTask.getNoticeDelayQueue().add(notDoneTask);
                    }

                    try {
                        String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
                        String touserid = properties.getTouserid();
                        UserData userData = WeixinUtil.getUserData(touserid, token);
                        String remindMsg = TemplateUtil.buildRemindMsg(properties.getTouserid(), userData.getNickName(), properties.getRemindtemplateid());
                        log.info("发送提醒消息内容:{}", remindMsg);
                        String sendUrl = properties.getTemplateurl() + token;
                        String response = HttpClientProxy.post(sendUrl, remindMsg);
                        log.info("发送提醒消息响应:{}", response);
                    } catch (Exception e) {
                        log.info("重试任务发送提醒消息时发生异常,异常信息:{}", e);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
